package utils

import (
	"fmt"
	"gim-server/consts"
	"github.com/gin-gonic/gin"
	"net/http"
	"runtime"
)

type response struct {
	Code    string      `json:"code"`
	Message interface{} `json:"message,omitempty"`
	Data    interface{} `json:"data,omitempty"`
	Ext     interface{} `json:"ext,omitempty"`
}

type PageListDto struct {
	Arr      interface{} `json:"arr"`
	PageNo   interface{} `json:"page_no,omitempty"`
	PageSize interface{} `json:"page_size"`
	LastId   interface{} `json:"last_id,omitempty"`
	Count    int64       `json:"count"`
}

func SUC(ctx *gin.Context, data interface{}, shouldLogger ...bool) {
	code := http.StatusOK
	resp := response{
		Code:    http.StatusText(code),
		Message: http.StatusText(code),
		Data:    data,
	}

	//这些设置的信息都是为了logger而设置的
	ctx.Set(consts.Code, code)
	if shouldLogger != nil && len(shouldLogger) > 0 && shouldLogger[0] {
		var respBody []byte
		if data != nil {
			respBody, _ = JsonMarshal(data)
		}
		ctx.Set(consts.RespBody, fmt.Sprintf("%s", string(respBody)))
		ctx.Set(consts.ShouldLogger, true)
	}
	ctx.JSON(http.StatusOK, resp)
}

type ErrArgs struct {
	Code string
	Err  interface{}
	Msg  interface{}
	Ext  interface{}
}

func ERR(ctx *gin.Context, args *ErrArgs) {
	if args.Err == "" {
		args.Err = http.StatusText(http.StatusInternalServerError)
	}
	resp := response{
		Code:    args.Code,
		Message: args.Msg,
		Ext:     args.Ext,
	}
	fmt.Printf("apiErr ===>>> %+v\n", args)
	ctx.Set(consts.Code, args.Code)
	ctx.Set(consts.Message, fmt.Sprintf("%+v", args.Msg))
	ctx.Set(consts.Error, fmt.Sprintf("%s", args.Err))
	pc, _, line, _ := runtime.Caller(1)
	ctx.Set(consts.Stack, fmt.Sprintf("%+v: %v行", runtime.FuncForPC(pc).Name(), line))
	ctx.Set(consts.ShouldLogger, true)
	ctx.JSON(http.StatusOK, resp)
}
